<?php
/*
 * Copyright (c) 2011 Todd Brady
 *
 * PS3Theatre is freely distributable under the terms of the MIT license.
 * For details, see the MIT-Liscence web site: http://www.opensource.org/licenses/mit-license.php 
 */
     include_once('../classes/TVDb.class.php');
     include_once('../includes/db_connect.php');
	 
	$seriesId=$_GET["seriesId"];
	$tvdbEpId=$_GET["tvdbEpId"]; 
	$seasonId=$_GET["seasonId"];
	$seasonIdText = '';
	$epId=$_GET["epId"];
	$epIdText = '';
	$backdrop=$_GET["backdrop"];
	$vignette=$_GET["vignette"];
	$poster=$_GET["poster"];
	$banner=$_GET["banner"];
	$seasonPoster=$_GET["seasonPoster"];
	$epScreenshot=$_GET['epScreenshot'];
	$cacheCompDir = $_SESSION['cacheCompDir'];
	$cacheHttpDir = $_SESSION['cacheHttpDir'];
	$subfolderPath = "TV Shows/";
	$seriesArray = '';
	$jsonString = '{';
	$xml = '';
	$width=1920;
	$comma=0;
	
	//where clause to only return rows we want
	$whereComma = "";
	$rowWhere = " and c.keyword in (";
	if($backdrop != ''){
		$rowWhere.=$whereComma."'backdrop'";
		$whereComma=", ";
	}
	
	if($vignette != ''){
		$rowWhere.=$whereComma."'vignette'";
		$whereComma=", ";
	}
	
	
	if($poster != ''){
		$rowWhere.=$whereComma."'poster'";
		$whereComma=", ";
	}
	
	if($banner != ''){
		$rowWhere.=$whereComma."'banner'";
		$whereComma=", ";
	}
	
	if($seasonPoster != ''){
		if($seasonIdText == ''){
			if($seasonId<10){
				$seasonIdText = "0".$seasonId;
			}else{
				$seasonIdText = $seasonId;
			}
		}
		$rowWhere.=$whereComma."'seasonPoster".$seasonIdText."'";
		$whereComma=", ";
	}
	
	if($epScreenshot != ''){
		if($seasonIdText == ''){
			if($seasonId<10){
				$seasonIdText = "0".$seasonId;
			}else{
				$seasonIdText = $seasonId;
			}
		}
		if($epIdText == ''){
			if($epId<10){
				$epIdText = "0".$epId;
			}else{
				$epIdText = $epId;
			}
		}
		$rowWhere.=$whereComma."'epScreenshot'";
		$whereComma=", ";
	}
	$rowWhere.=')';
	
	$cacheQueryStr = "SELECT c.id, c.type_id, c.link_id, c.keyword, c.subfolder_path, c.filename FROM tbl_cacheimage c,tbl_types t WHERE c.type_id=t.id AND t.type='TV Shows'";
	
	if($epScreenshot != ''){
		$cacheQueryStr.=" and c.link_id=$tvdbEpId ";
	}else{
		$cacheQueryStr.=" and c.link_id=$seriesId ";
	}
	
	$cacheQueryStr.=$rowWhere;
	
	$cacheQuery = mysql_query($cacheQueryStr) or die(mysql_error());
	$backdropRow = '';
	$vignetteRow = '';
	$posterRow = ''; 
	$bannerRow = '';
	$seasonPosterRow = '';
	$epScreenshotRow = '';

while ($row = mysql_fetch_array($cacheQuery)) {
	if($row['keyword'] == 'backdrop'){
		$backdropRow = $row;
	}else if($row['keyword'] == 'vignette'){
		$vignetteRow = $row;
	}else if($row['keyword'] == 'poster'){
		$posterRow = $row;
	}else if($row['keyword'] == 'banner'){
		$bannerRow = $row;
	}else if(substr($row['keyword'],0,12) == 'seasonPoster'){
		$seasonPosterRow = $row;
	}else if($row['keyword'] == 'epScreenshot'){
		$epScreenshotRow = $row;
	}
} 
	
	$tvapi = new TVDb('CE4CE0C779385D53');
	
	if($backdrop != ''){
		if($backdropRow != ''){
			//already cached, just print url
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "backdropSrc" : "'.$cacheHttpDir.$backdropRow['subfolder_path'].$backdropRow['filename'].'"';
			
		}else{
			//get image from server, save to file and database
			if($xml == ''){
				$xml = simplexml_load_file('http://thetvdb.com/api/CE4CE0C779385D53/series/'.$seriesId.'/banners.xml');
				$bannerAr = $xml->xpath("/Banners/Banner");
				$i=0;
				while($i < count($bannerAr) && $bannerAr[$i]->BannerType == 'fanart' && substr($bannerAr[$i]->BannerType2,0,4) != $width){
					$i++;
				}
	
				$backdropSrc = 'http://thetvdb.com/banners/'.$bannerAr[$i]->BannerPath;
			}
			
			$ext = substr($backdropSrc,strrpos($backdropSrc,'.'),strlen($backdropSrc));
			$image = file_get_contents($backdropSrc);
			
			if(!is_dir ($cacheCompDir.$subfolderPath)){
				mkdir($cacheCompDir.$subfolderPath);
			}
			
			file_put_contents($cacheCompDir.$subfolderPath.$seriesId.'-backdrop'.$ext, $image);
			
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "backdropSrc" : "'.$cacheHttpDir.$subfolderPath.$seriesId.'-backdrop'.$ext.'"';
			
			//insert record into cache image table
			$insertQuery = sprintf("INSERT INTO tbl_cacheimage (type_id,link_id,keyword,subfolder_path,filename) select id,%s,'%s','%s','%s' FROM tbl_types where type='%s'", 
							   	   mysql_real_escape_string($seriesId),
								   mysql_real_escape_string('backdrop'),
								   mysql_real_escape_string($subfolderPath),
								   mysql_real_escape_string($seriesId.'-backdrop'.$ext),
								   mysql_real_escape_string('TV Shows'));

			//insert movie record
			mysql_query($insertQuery) or die('error inserting backdrop record: query: '.$insertQuery.'error:'.mysql_error());
			
		}
	}
	
	if($vignette != ''){
		if($vignetteRow != ''){
			//already cached, just print url
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "vignetteSrc" : "'.$cacheHttpDir.$vignetteRow['subfolder_path'].$vignetteRow['filename'].'"';
			
		}else{
			//get image from server, save to file and database
			if($xml == ''){
				$xml = simplexml_load_file('http://thetvdb.com/api/CE4CE0C779385D53/series/'.$seriesId.'/banners.xml');
				$bannerAr = $xml->xpath("/Banners/Banner");
				$i=0;
				while($i < count($bannerAr) && $bannerAr[$i]->BannerType == 'fanart' && substr($bannerAr[$i]->BannerType2,0,4) != $width){
					$i++;
				}
	
				$backdropSrc = 'http://thetvdb.com/banners/'.$bannerAr[$i]->VignettePath;
			}
			
			$ext = substr($backdropSrc,strrpos($backdropSrc,'.'),strlen($backdropSrc));
			$image = file_get_contents($backdropSrc);
			
			if(!is_dir ($cacheCompDir.$subfolderPath)){
				mkdir($cacheCompDir.$subfolderPath);
			}
			
			file_put_contents($cacheCompDir.$subfolderPath.$seriesId.'-vignette'.$ext, $image);
			
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "vignetteSrc" : "'.$cacheHttpDir.$subfolderPath.$seriesId.'-vignette'.$ext.'"';
			
			//insert record into cache image table
			$insertQuery = sprintf("INSERT INTO tbl_cacheimage (type_id,link_id,keyword,subfolder_path,filename) select id,%s,'%s','%s','%s' FROM tbl_types where type='%s'", 
							   	   mysql_real_escape_string($seriesId),
								   mysql_real_escape_string('vignette'),
								   mysql_real_escape_string($subfolderPath),
								   mysql_real_escape_string($seriesId.'-vignette'.$ext),
								   mysql_real_escape_string('TV Shows'));

			//insert movie record
			mysql_query($insertQuery) or die('error inserting vignette record: query: '.$insertQuery.'error:'.mysql_error());
			
		}
	}
	
	if($poster != ''){
		if($posterRow != ''){
			//already cached, just print url
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "posterSrc" : "'.$cacheHttpDir.$posterRow['subfolder_path'].$posterRow['filename'].'"';
			
		}else{
			//get image from server, save to file and database
			if($seriesArray == ''){
				$seriesArray = $tvapi->GetSerieData($seriesId);
			}
			
			$posterSrc = 'http://thetvdb.com/banners/'.$seriesArray['posterUrl'];
			$ext = substr($posterSrc,strrpos($posterSrc,'.'),strlen($posterSrc));
			$image = file_get_contents($posterSrc);
			
			if(!is_dir ($cacheCompDir.$subfolderPath)){
				mkdir($cacheCompDir.$subfolderPath);
			}
			
			file_put_contents($cacheCompDir.$subfolderPath.$seriesId.'-poster'.$ext, $image);
			
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "posterSrc" : "'.$cacheHttpDir.$subfolderPath.$seriesId.'-poster'.$ext.'"';
			
			//insert record into cache image table
			$insertQuery = sprintf("INSERT INTO tbl_cacheimage (type_id,link_id,keyword,subfolder_path,filename) select id,%s,'%s','%s','%s' FROM tbl_types where type='%s'", 
							   	   mysql_real_escape_string($seriesId),
								   mysql_real_escape_string('poster'),
								   mysql_real_escape_string($subfolderPath),
								   mysql_real_escape_string($seriesId.'-poster'.$ext),
								   mysql_real_escape_string('TV Shows'));

			//insert movie record
			mysql_query($insertQuery) or die('error inserting poster record: query: '.$insertQuery.'error:'.mysql_error());
		}
	}
	
	if($banner != ''){
		if($bannerRow != ''){
			//already cached, just print url
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "bannerSrc" : "'.$cacheHttpDir.$bannerRow['subfolder_path'].$bannerRow['filename'].'"';
			
		}else{
			//get image from server, save to file and database
			if($seriesArray == ''){
				$seriesArray = $tvapi->GetSerieData($seriesId);
			}
			
			$bannerSrc = 'http://thetvdb.com/banners/'.$seriesArray['bannerUrl'];
			$ext = substr($bannerSrc,strrpos($bannerSrc,'.'),strlen($bannerSrc));
			$image = file_get_contents($bannerSrc);
			
			if(!is_dir ($cacheCompDir.$subfolderPath)){
				mkdir($cacheCompDir.$subfolderPath);
			}
			
			file_put_contents($cacheCompDir.$subfolderPath.$seriesId.'-banner'.$ext, $image);
			
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "bannerSrc" : "'.$cacheHttpDir.$subfolderPath.$seriesId.'-banner'.$ext.'"';
			
			//insert record into cache image table
			$insertQuery = sprintf("INSERT INTO tbl_cacheimage (type_id,link_id,keyword,subfolder_path,filename) select id,%s,'%s','%s','%s' FROM tbl_types where type='%s'", 
							   	   mysql_real_escape_string($seriesId),
								   mysql_real_escape_string('banner'),
								   mysql_real_escape_string($subfolderPath),
								   mysql_real_escape_string($seriesId.'-banner'.$ext),
								   mysql_real_escape_string('TV Shows'));

			//insert movie record
			mysql_query($insertQuery) or die('error inserting banner record: query: '.$insertQuery.'error:'.mysql_error());
		}
	}
	
	if($seasonPoster != ''){
		if($seasonPosterRow != ''){
			//already cached, just print url
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "seasonPosterSrc" : "'.$cacheHttpDir.$seasonPosterRow['subfolder_path'].$seasonPosterRow['filename'].'"';
		}else{
			//get image from server, save to file and database
			if($xml == ''){
				$xml = simplexml_load_file('http://thetvdb.com/api/CE4CE0C779385D53/series/'.$seriesId.'/banners.xml');
			}
				$bannerAr = $xml->xpath("/Banners/Banner");

				$i=0;
				while($i < count($bannerAr) && ($bannerAr[$i]->Season == '' || $bannerAr[$i]->Season != $seasonId)){				
					$i++;
				}
	
				$seasonPosterSrc = 'http://thetvdb.com/banners/'.$bannerAr[$i]->BannerPath;
			
			$ext = substr($seasonPosterSrc,strrpos($seasonPosterSrc,'.'),strlen($seasonPosterSrc));
			$image = file_get_contents($seasonPosterSrc);
			
			if(!is_dir ($cacheCompDir.$subfolderPath)){
				mkdir($cacheCompDir.$subfolderPath);
			}
			
			file_put_contents($cacheCompDir.$subfolderPath.$seriesId.'-seasonPoster'.$seasonIdText.$ext, $image);
			
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "seasonPosterSrc" : "'.$cacheHttpDir.$subfolderPath.$seriesId.'-seasonPoster'.$seasonIdText.$ext.'"';
			
			//insert record into cache image table
			$insertQuery = sprintf("INSERT INTO tbl_cacheimage (type_id,link_id,keyword,subfolder_path,filename) select id,%s,'%s','%s','%s' FROM tbl_types where type='%s'", 
							   	   mysql_real_escape_string($seriesId),
								   mysql_real_escape_string('seasonPoster'.$seasonIdText),
								   mysql_real_escape_string($subfolderPath),
								   mysql_real_escape_string($seriesId.'-seasonPoster'.$seasonIdText.$ext),
								   mysql_real_escape_string('TV Shows'));

			//insert movie record
			mysql_query($insertQuery) or die('error inserting season poster record: query: '.$insertQuery.'error:'.mysql_error());
		}
	}
	
	if($epScreenshot != ''){
		if($epScreenshotRow != ''){
			//already cached, just print url
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "epScreenshotSrc" : "'.$cacheHttpDir.$epScreenshotRow['subfolder_path'].$epScreenshotRow['filename'].'"';
		}else{
			//get image from server, save to file and database
			$epXml = simplexml_load_file('http://thetvdb.com/api/CE4CE0C779385D53/series/'.$seriesId.'/default/'.$seasonId.'/'.$epId.'/en.xml');
			
			$epAr = $epXml->xpath("/Data/Episode");
			$epScreenshotSrc = 'http://thetvdb.com/banners/'.$epAr[0]->filename;

			$ext = substr($epScreenshotSrc,strrpos($epScreenshotSrc,'.'),strlen($epScreenshotSrc));
			$image = file_get_contents($epScreenshotSrc);
			
			if(!is_dir ($cacheCompDir.$subfolderPath)){
				mkdir($cacheCompDir.$subfolderPath);
			}
			
			
			file_put_contents($cacheCompDir.$subfolderPath.$seriesId.'-epScreenshot'.$seasonIdText.$epIdText.$ext, $image);
			
			if($comma != 0){
				$jsonString.=', ';
				$comma++;
			}
		
			$jsonString.=' "epScreenshotSrc" : "'.$cacheHttpDir.$subfolderPath.$seriesId.'-epScreenshot'.$seasonIdText.$epIdText.$ext.'"';
			
			//insert record into cache image table
			$insertQuery = sprintf("INSERT INTO tbl_cacheimage (type_id,link_id,keyword,subfolder_path,filename) select id,%s,'%s','%s','%s' FROM tbl_types where type='%s'", 
							   	   mysql_real_escape_string($tvdbEpId),
								   mysql_real_escape_string('epScreenshot'),
								   mysql_real_escape_string($subfolderPath),
								   mysql_real_escape_string($seriesId.'-epScreenshot'.$seasonIdText.$epIdText.$ext),
								   mysql_real_escape_string('TV Shows'));

			//insert movie record
			mysql_query($insertQuery) or die('error inserting season poster record: query: '.$insertQuery.'error:'.mysql_error());
		}
	}
	
	echo $jsonString.'}';
?>